﻿using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

using ABCat.Shared.Properties;

namespace ABCat.Shared
{
	public sealed class LoginInfo : ICloneable, INotifyPropertyChanged
	{
		#region + Events +

		public event PropertyChangedEventHandler PropertyChanged;

		#endregion
		#region + Fields +

		private readonly string _cryptPassword = Extensions.GenerateRandomString(16, 300);

		private string _login;
		private string _password;
		private bool _saveCoockies;

		public bool IsCancelled { get; set; }

		#endregion
		#region + Properties +

		public string Login
		{
			get { return _login; }
			set
			{
				if (value == _login) return;
				_login = value;
				OnPropertyChanged();
			}
		}

		#endregion
		#region + Logic +

		public bool Check()
		{
			return !string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(_password);
		}

		public LoginInfo()
		{
		}

		public object Clone()
		{
			var clone = new LoginInfo();
			clone.Login = Login;
			clone.SetPassword(GetPassword());
			return clone;
		}

		public string GetPassword()
		{
			return string.IsNullOrEmpty(_password) ? null : _password.Decrypt(_cryptPassword);
		}

		public void SetPassword(string password)
		{
			_password = string.IsNullOrEmpty(password) ? null : password.Encrypt(_cryptPassword);
			OnPropertyChanged("Password");
		}

		[NotifyPropertyChangedInvocator]
		private void OnPropertyChanged([CallerMemberName] string propertyName = null)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
		}

		#endregion
	}
}